app_Ctrl.controller('mallCtrl',function($timeout,$scope,$ionicTabsDelegate ,$cordovaToast,Storage,$ionicLoading,$state,mineModule){
  
  // 初始化设置上拉加载更多为有效
  $scope.moreDataCoupon = true;//优惠券
  $scope.moreDataGood = true;//礼品券

  //获取优惠券
    $scope.coupon_params = {
      page:1,
      rows:10,
      couponType:1
    }
    $scope.get_coupons = function(){
      mineModule.http("getGoodList",$scope.coupon_params).then(function(res){
        // console.log("coupon:"+JSON.stringify(res))
        if(res.length>0){
          $scope.coupons = res
          $scope.NODATA_show_coupon = "";
        }else{
          // alert("暂无相关数据！")
          $scope.NODATA_show_coupon = '暂无相关数据！';
        }
      })
    }
    $scope.get_coupons();

    //下拉刷新数据；
    $scope.doRefresh_coupon = function(){
      $scope.moreDataCoupon = true;//优惠券 //重置下拉加载更多；
      $scope.nomoreData_coupon = false;//隐藏没有数据的提示
      // console.log('开始下拉刷新数据。。。。');
      $scope.coupon_params.page = 1;
      mineModule.http("getGoodList",$scope.coupon_params).then(function(res){
        $scope.$broadcast('scroll.refreshComplete');
        if(res.length>0){
          $scope.coupons = res
          // console.log("这是下拉刷新获取的数据："+JSON.stringify(res));
          $scope.NODATA_show_coupon = ' ';
        }else{
          $scope.NODATA_show_coupon = '暂无相关数据！';
        }
      })
     var timer = setTimeout(function(){
      $scope.$broadcast('scroll.refreshComplete');
     },3000);
    }

    //上拉加载更多
    $scope.loadMoreCoupon = function(){
      $scope.coupon_params.page++;
      var timer = null;
      mineModule.http("getGoodList", $scope.coupon_params).then(function (res) {
        // console.log("1:" +JSON.stringify(res));
          $scope.res = res;
          if ( $scope.res) {
            if ( $scope.res.length !== 0) {
              for (var i = 0; i < $scope.res.length; i++) {
                $scope.coupons.push($scope.res[i]);
              }
            }
            if ( $scope.res.length === 0) {
              $scope.moreDataCoupon  = false;
              $scope.nomoreData_coupon = true;
            }
            timer = $timeout(function () {
              $scope.$broadcast('scroll.infiniteScrollComplete');
            }, 1500);
          }else{
            $scope.moreDataCoupon = false;
            $scope.nomoreData_coupon = true;
            $scope.$broadcast('scroll.infiniteScrollComplete');
          }
      })
    }

    //礼品券；
    $scope.good_params = {
      page:1,
      rows:10,
      couponType:2
    }
    $scope.get_goods = function(){
      mineModule.http("getGoodList",$scope.good_params).then(function(res){
        // console.log("礼品："+JSON.stringify(res));
        if(res.length>0){
          $scope.goods = res;
          // console.log("good:"+JSON.stringify(res.data['list']));
          $scope.NODATA_show_goods = ' ';
        }else{
          // alert('暂无相关数据！')
          $scope.NODATA_show_goods = '暂无相关数据！';
        }
      
      })
    }
    $scope.get_goods();

    //下拉刷新礼品券；
    $scope.doRefresh_gift = function(){
      $scope.moreDataGood = true;//优惠券 //重置下拉加载更多；
      $scope.nomoreData_good = false;//隐藏没有数据的提示
      // console.log('开始下拉刷新数据。。。。');
      $scope.good_params.page = 1;
      mineModule.http("getGoodList",$scope.good_params).then(function(res){
        $scope.$broadcast('scroll.refreshComplete');
        // console.log("礼品："+JSON.stringify(res));
        if(res.length>0){
          $scope.goods = res;
          $scope.NODATA_show_goods = ' ';
        }else{
          // alert('暂无相关数据！')
          $scope.NODATA_show_goods = '暂无相关数据！';
        }
      
      })
     var timer = setTimeout(function(){
      $scope.$broadcast('scroll.refreshComplete');
     },3000);
    }

    //上拉加载更多
    $scope.loadMoreGood = function(){
      $scope.good_params.page++;
      var timer = null;
      mineModule.http("getGoodList", $scope.good_params).then(function (res) {
        // console.log("2:" +JSON.stringify(res));
        // if(res.code = 10000){
        //   $scope.g_res = res.data.list;
          $scope.g_res = res;
          if ( $scope.g_res) {
            if ( $scope.g_res.length !== 0) {
              for (var i = 0; i < $scope.g_res.length; i++) {
                $scope.goods.push($scope.g_res[i]);
              }
            }
            if ( $scope.g_res.length === 0) {
              $scope.moreDataGood  = false;
              $scope.nomoreData_good = true;
            }
            timer = $timeout(function () {
              $scope.$broadcast('scroll.infiniteScrollComplete');
            }, 1500);
          }else{
            $scope.moreDataGood  = false;
            $scope.nomoreData_good = true;
            $scope.$broadcast('scroll.infiniteScrollComplete');
          }
        // }else{
        //   alert("获取数据出错了！");
        // }
      })
    }
})

//商品详情goodsCtrl
.controller('goodsCtrl',function($ionicPopup,$state,Storage,Common,md5,$ionicLoading,$ionicModal,loginModule,$scope,$ionicTabsDelegate,$ionicHistory,$stateParams,mineModule){
  $scope.goback=function(){
    $ionicHistory.goBack();
  }
  //登录页面
  $ionicModal.fromTemplateUrl('templates/modal.html', {
      scope: $scope
  }).then(function(modal) {
      $scope.modal = modal;
  });
  //登录页面
  //获取传递过来的id
  $scope.good_id = $stateParams.id;
  // console.log("礼品："+ $scope.good_id );

  //通过ID获取商品详情
  $scope.get_good_details = function(){
     var params = {
      goodsId:$scope.good_id
    }
    mineModule.http("getGoodDetail",params).then(function(res){
      // console.log("good:"+JSON.stringify(res));
      if(res.code = 10000){
        $scope.good_details = res.info;
        //格式化要显示的数据
        $scope.good_details.levels = $scope.good_details.levels.join(" ");
        if($scope.good_details.couponInfo.beginTime){
           $scope.good_details.couponInfo.beginTime = $scope.good_details.couponInfo.beginTime.split(" ")[0];
        }
        if( $scope.good_details.couponInfo.endTime){
           $scope.good_details.couponInfo.endTime = $scope.good_details.couponInfo.endTime.split(" ")[0];
        }
        // console.log("good详情："+JSON.stringify($scope.good_details));
      }else{
        alert("获取数据出错了！")
      }

    })
  }
  $scope.get_good_details();
  //判断是否登录
  $scope.go_confirm = function(){
    if(Storage.ls_get("user_infos")){
      //登录过直接跳转确认订单页面
      $state.go("tab.confirm_order",{id:$scope.good_id});
    }else{
      $scope.modal.show();
      // alert("登录后才能购买！")
      //未登录
        //显示登录模块
          //登录成功后跳转确认订单页面
    }
  }

  
//new 登录注册模块
// 10200 //请求成功!  10201 // 验证码失效  10202 // 该手机尚未注册!  10203 // 手机号已经被注册  10204 //手机号或者密码错误!
    //登录方式切换
      //默认初始化显示快登陆
      $scope.pwd_login_2 = false;
      $scope.test_code_login_2 = true;
      $scope.show_M = 0;
    $scope.changeModel = function(n){
      $scope.show_M = n;
      if( n == 0){
         $scope.pwd_login_2 = false;
         $scope.test_code_login_2 = true;
      }else{
         $scope.pwd_login_2 = true;
         $scope.test_code_login_2 = false;
      }
    }
    //登录注册切换
    $scope.display_login = true;
    $scope.display_register = false;
    $scope.m_title = "登录"
    $scope.change_page = function(num){
      if(num == 0){
        $scope.display_login = true;
        $scope.display_register = false;
        $scope.m_title = "登录"
      }
      if(num == 1){
        $scope.display_login = false;
        $scope.display_register = true;
        $scope.m_title = "注册"
      }
      $scope.captcha = {
        paracont: '获取验证码',
        is_disable: false,
        paraevent: true
      };
    }

    //登录逻辑(快捷登录)
    //获取验证码
    $scope.user_info = {};
    $scope.captcha = {
      paracont: '获取验证码',
      is_disable: false,
      paraevent: true
    };
    $scope.get_test_code = function(e){
      var mobile =  $scope.user_info.user_num;
      var area = document.getElementById('mgood_DL_area').value;
      // alert(area);
      if ($scope.captcha.paraevent) {
        if (Common.checkMobile(mobile)) {
          // console.log(mobile);
          $ionicLoading.show({
            template: '获取验证码...'
          });
          //调取验证码服务；
          Common.countDown($scope.captcha);
          loginModule.get_captcha(mobile).then(function(res){
            $ionicLoading.hide();
            if(res.result == 10202){
              $scope.change_page(1)//切换到登录页面
              $cordovaToast.show('该手机尚未注册,注册后可快捷登录!', 'long', 'center');
              // alert("该手机尚未注册,注册后可快捷登录!");
            }
          })
        }else{
          //手机号码不对；
        }
      } else {
          e.preventDefault();
      }
    }
    // 快捷登录(登录按钮)
    $scope.LOGIN = function(){
      // console.log("开始验证了+++++++++++++++++++++++++++++++++++++")
      var mobile =  $scope.user_info.user_num;
      var code = $scope.user_info.test_code;
      //正则及相关验证；
      var _rep = /\d{6}/.test(code);
      var _mobile = /^\d{5,}$/.test(mobile);
      if(mobile&&_mobile){//验证通过；
        $scope.phone_tc = " "
        if((_rep && code.length === 6)){//tongguo 
          $ionicLoading.show({
            template: '正在登录中...'
          });
          $scope.test_code_tc = " "
          loginModule.login(mobile,code).then(function(res){
            $ionicLoading.hide();
            // console.log("快捷登录的结果："+JSON.stringify(res))
            switch(res.result){//10200 //请求成功!10201 // 验证码失效10202 // 该手机尚未注册!10203 // 手机号已经被注册10204 //手机号或者密码错误!
              case 10200:
                // alert("请求成功");
                //掉用成功的方法
                $scope.member_info = res.member //绑定会员相关数据
                // console.log("会员相关信息："+ $scope.member_info);
                //$scope.top_info = true; //切换已登录的模板
                $scope.no_user_infos = false;
                // $scope.no_user_infos = false;//显示会员信息区域
                Storage.ls_set("user_infos",$scope.member_info);//将会员信息本地存储
                $scope.modal.hide();//将会员信息本地存储
                //$state.go("tab.confirm_order",{id:$scope.coupon_id});//跳转对应的优惠券详情页面//////////////////////////
                //隐藏登录入口
                $scope.no_login = false;
                //清除相关用户信息
                $scope.user_info.user_num = "";
                $scope.user_info.test_code = "";

                //记住密码（防止验证码登录后修改密码报错）
                $scope.id_pwd = {
                  user_num:mobile,
                  user_pwd:''
                };
                Storage.ls_set("user&pwd",$scope.id_pwd);//记住账号及密码

                $cordovaToast.show('登录成功!', 'long', 'center');
                break;
              case 10201:
                // alert("");
                $cordovaToast.show('验证码失效或错误!', 'long', 'center');
                break;
              case 10202:
                // alert("");
                $cordovaToast.show('该手机尚未注册', 'long', 'center');
                break;
              case 10203:
                // alert("");
                $cordovaToast.show('手机号已经被注册', 'long', 'center');
                break;
              case 10204:
                // alert("");
                $cordovaToast.show('手机号或者密码错误', 'long', 'center');
                break;
              default:
                // alert("");
                $cordovaToast.show('出错了，稍后再试', 'long', 'center');
            }
          })
        }else{//手机号错误
          $scope.test_code_tc = "请输入6位正确的验证码"
        }
      }else{//验证码未填或填错；
        $scope.phone_tc = "请输入正确的手机号码"
      }
    }
    //清除验证状态
    $scope.phone_test = function(){//手机号码状态清除
      $scope.phone_tc = " ";
      //账号密码登录状态
      $scope.reg_notice_phone = "";//手机号正则状态清除
      $scope.pwd_login_res = "";//登陆结果状态
    }
    $scope.verification_test = function(){//验证码状态清除
      $scope.test_code_tc = " ";
      //账号密码登录状态
      $scope.reg_notice_pwd = "";//pwd正则状态清除
      $scope.pwd_login_res = "";//登陆结果状态
    }

//账号密码登录
    $scope.n_user_info = {};
    $scope.login_pwd = function(){
      
      var p_user = $scope.n_user_info.user_num;
      var P_pwd = $scope.n_user_info.user_pwd;
      //正则验证；
      // var reg_pwd = /^[a-zA-Z]\w{5,17}$/;
      var reg_mobile = /^\d{5,}$/;

      if(reg_mobile.test(p_user)){//手机号验证通过
        if(P_pwd&&P_pwd.length>7){//密码正则通过
          $ionicLoading.show({
            template: '正在登录中...'
          });
          var md5_pwd = md5.createHash(P_pwd);
          // console.log(md5_pwd);
          //进行登录
          loginModule.n_login(p_user,md5_pwd).then(function(res){
            $ionicLoading.hide();
            // console.log("会员细信息："+JSON.stringify(res));
            switch(res.result){//10200 //请求成功!10201 // 验证码失效10202 // 该手机尚未注册!10203 // 手机号已经被注册10204 //手机号或者密码错误!
              case 10200:
                // alert("请求成功");
                //显示会员相关信息
                $scope.member_info = res.member;
                Storage.ls_set("user_infos",res.member);
                $scope.no_user_infos = false;//显示个人信息这块
                $scope.no_login = false//关闭登录入口
                //隐藏登录
                $scope.modal.hide();
                //$state.go("tab.confirm_order",{id:$scope.coupon_id});//跳转对应的优惠券详情页面//////////////////////////
                // 记住密码；
                if($scope.ischecked){
                  // alert("记住密码")
                  Storage.ls_set("user&pwd", $scope.n_user_info);//记住账号及密码
                }else{
                  Storage.ls_delete("user&pwd");//账号
                  // alert("删除密码")
                  $scope.n_user_info = {};//删除账号及密码
                }
                $cordovaToast.show('登录成功!', 'long', 'center');
                break;
              case 10201:
                // alert("验证码失效");
                $scope.pwd_login_res = "验证码失效或错误"
                break;
              case 10202:
                // alert("该手机尚未注册");
                $scope.pwd_login_res = "该手机尚未注册"
                break;
              case 10203:
                // alert("手机号已经被注册");
                $scope.pwd_login_res = "手机号已经被注册"
                break;
              case 10204:
                // alert("手机号或者密码错误");
                $scope.pwd_login_res = " 手机号或者密码错误"
                break;
              default:
                // alert("出错了，稍后再试");
                $scope.pwd_login_res = "出错了，稍后再试"
            }
           
          })
        }else{//密码正则未通过
           $scope.reg_notice_pwd = "数字和者字母（6到18位）"
        }
      }else{//手机号正则不通过
        $scope.reg_notice_phone = "手机号不正确"
      }

    }
  //获取或设置复选框是否选中
  $scope.ischecked = false;
  //点击切换显密码
  $scope.show_pwd_value = "显示"
  $scope.show_pwd = function(){
    var input = document.getElementById("pwd");
    if(input.type == "text"){
      // console.log("pwd")
      input.type = "password";
      $scope.show_pwd_value = "显示"
    }else{
      // console.log("text")
      input.type = "text";
      $scope.show_pwd_value = "隐藏"
    }

  }

   //注册模块
  $scope.register_info = {};//存放用户注册信息
  $scope.register = function(){
   
    //正则验证
    var r_mobile = $scope.register_info.phone
    var r_pwd = $scope.register_info.pwd;
    var r_code = $scope.register_info.code;
    var _mobile = /^\d{5,}$/.test(r_mobile);
    var _code = /\d{6}/.test(r_code);
    var area = document.getElementById('mgood_ZC_area').value;
    // alert(area);
    if(_mobile){
      if(r_pwd && r_pwd.length>7 ){
        if(_code){
          $ionicLoading.show({
            template: '正在注册中...'
          });
          var params = {
            m_phone : r_mobile,
            code : r_code ,
            m_pass : md5.createHash( r_pwd ),
            area:area
          };
          loginModule.register(params).then(function(res){
            // console.log("注册结果"+JSON.stringify(res));
            $ionicLoading.hide();
            switch(res.result){
              case 10200:
                // alert("注册成功,马上登录");
                $scope.change_page(0);//切换至登录模块
                $cordovaToast.show('注册成功,马上登录!', 'long', 'center');
                break;
              case 10201:
                $scope.r_pwd_login_res_code = "验证码失效或错误";
                break;
              case 10202:
                $scope.r_pwd_login_res = "该手机尚未注册";
                break;
              case 10203:
                $scope.r_pwd_login_res = "手机号已经被注册";
                break;
              case 10204:
                $scope.r_pwd_login_res = " 手机号或者密码错误";
                break;
              default:
                $scope.r_pwd_login_res = "出错了，稍后再试";
            }
          })
        }else{
          $ionicPopup.alert({
            title: '提示',
            template: '请输入6位数字验证码！'
          });
        }
      }else{
        // alert("密码为8位以上数字或字母")
        $scope.r_pwd_num = "密码为8位以上数字或字母"
      }
    }else{
      // alert("手机号码不正确")
      $scope.r_phone_num = "手机号码不正确"
    }
   
  }
  //清除注册提示状态
  $scope.hide_notice = function(){
    $scope.r_phone_num = "";
    $scope.r_pwd_num = "";
    $scope.r_pwd_login_res_code = "";
    $scope.r_pwd_login_res = "";
  }
  // 验证码(注册模块)
  $scope.register_code = function(e){
    var phone =  $scope.register_info.phone;
    var area = document.getElementById('mgood_ZC_area').value;
    // alert(area);
    // alert(phone);
    if ($scope.captcha.paraevent) {
      if (Common.checkMobile(phone)){
        $ionicLoading.show({
          template: '获取验证码...'
        });
        //调取验证码服务；
        loginModule.reg_captcha(phone,area).then(function(res){
          $ionicLoading.hide();
          // console.log(res);
          if(res.result == "10203"){
            $scope.r_pwd_login_res = "手机号已经注册，请直接登录";
          }else{
            Common.countDown($scope.captcha);
          }
        })
      }else{
        //手机号码不对；
      }
    } else {
        e.preventDefault();
    }
  }
  //重置验证码提示消息
  $scope.set_code_notice = function(){
     $scope.r_pwd_login_res = " "
  }
  //切换密码
  $scope.ischecked = true;//初始化为记住密码状态
  $scope.toggle_pwd = function(){
    if($scope.ischecked){
      $scope.ischecked = false;
    }else{
      $scope.ischecked = true;
    }
  }

    
})

//优惠券详情
.controller('coupon_detailCtrl',function($ionicPopup,Common,md5,$ionicLoading,$ionicModal,loginModule,$scope,$state,Storage,$ionicTabsDelegate,$ionicHistory,$stateParams,mineModule){
  $scope.goback=function(){
    $ionicHistory.goBack();
  }

  //登录页面
  $ionicModal.fromTemplateUrl('templates/modal.html', {
      scope: $scope
  }).then(function(modal) {
      $scope.modal = modal;
  });
  //登录页面

  $scope.coupon_id = $stateParams.id;
  // console.log("优惠券："+ $scope.coupon_id );
  //获取优惠券信息详情；
  $scope.get_coupons_details = function(){
    var params = {
      goodsId:$scope.coupon_id
    }
    mineModule.http("getGoodDetail",params).then(function(res){
      console.log("优惠券详情："+JSON.stringify(res))
      if( res.code == 10000 ){
        $scope.coupons_details = res.info;
        $scope.coupons_details.levels = $scope.coupons_details.levels.join(" ");
        if($scope.coupons_details.couponInfo.beginTime){
          $scope.coupons_details.couponInfo.beginTime = $scope.coupons_details.couponInfo.beginTime.split(" ")[0];
        }
        if( $scope.coupons_details.couponInfo.endTime){
          $scope.coupons_details.couponInfo.endTime = $scope.coupons_details.couponInfo.endTime.split(" ")[0];
        }
      }else{
        alert("获取数据失败");
      }
    })
  }
  $scope.get_coupons_details();

  $scope.go_confirm = function(){
    if(Storage.ls_get("user_infos")){
      //登录过直接跳转确认订单页面
      $state.go("tab.confirm_order",{id:$scope.coupon_id});
    }else{
      $scope.modal.show();
      // alert("登录后才能购买！")
      //未登录
        //显示登录模块
          //登录成功后跳转确认订单页面
    }
  }


//new 登录注册模块
// 10200 //请求成功!  10201 // 验证码失效  10202 // 该手机尚未注册!  10203 // 手机号已经被注册  10204 //手机号或者密码错误!
    //登录方式切换
      //默认初始化显示快登陆
      $scope.pwd_login_2 = false;
      $scope.test_code_login_2 = true;
      $scope.show_M = 0;
    $scope.changeModel = function(n){
      $scope.show_M = n;
      if( n == 0){
         $scope.pwd_login_2 = false;
         $scope.test_code_login_2 = true;
      }else{
         $scope.pwd_login_2 = true;
         $scope.test_code_login_2 = false;
      }
    }
    //登录注册切换
    $scope.display_login = true;
    $scope.display_register = false;
    $scope.m_title = "登录"
    $scope.change_page = function(num){
      if(num == 0){
        $scope.display_login = true;
        $scope.display_register = false;
        $scope.m_title = "登录"
      }
      if(num == 1){
        $scope.display_login = false;
        $scope.display_register = true;
        $scope.m_title = "注册"
      }
      $scope.captcha = {
        paracont: '获取验证码',
        is_disable: false,
        paraevent: true
      };
    }

    //登录逻辑(快捷登录)
    //获取验证码
    $scope.user_info = {};
    $scope.captcha = {
      paracont: '获取验证码',
      is_disable: false,
      paraevent: true
    };
    $scope.get_test_code = function(e){
      var mobile =  $scope.user_info.user_num;
      var area = document.getElementById('mcoupon_DL_area').value;
      // alert(area);
      if ($scope.captcha.paraevent) {
        if (Common.checkMobile(mobile)) {
          // console.log(mobile);
          $ionicLoading.show({
            template: '获取验证码...'
          });
          //调取验证码服务；
          Common.countDown($scope.captcha);
          loginModule.get_captcha(mobile,area).then(function(res){
            $ionicLoading.hide();
            if(res.result == 10202){
              $scope.change_page(1)//切换到登录页面
              $cordovaToast.show('该手机尚未注册,注册后可快捷登录!', 'long', 'center');
              // alert("该手机尚未注册,注册后可快捷登录!");
            }
          })
        }else{
          //手机号码不对；
        }
      } else {
          e.preventDefault();
      }
    }
    // 快捷登录(登录按钮)
    $scope.LOGIN = function(){
      // console.log("开始验证了+++++++++++++++++++++++++++++++++++++")
      var mobile =  $scope.user_info.user_num;
      var code = $scope.user_info.test_code;
      //正则及相关验证；
      var _rep = /\d{6}/.test(code);
      var _mobile = /^\d{5,}$/.test(mobile);
      if(mobile&&_mobile){//验证通过；
        $scope.phone_tc = " "
        if((_rep && code.length === 6)){//tongguo 
          $ionicLoading.show({
            template: '正在登录中...'
          });
          $scope.test_code_tc = " "
          loginModule.login(mobile,code).then(function(res){
            $ionicLoading.hide();
            // console.log("快捷登录的结果："+JSON.stringify(res))
            switch(res.result){//10200 //请求成功!10201 // 验证码失效10202 // 该手机尚未注册!10203 // 手机号已经被注册10204 //手机号或者密码错误!
              case 10200:
                // alert("请求成功");
                //掉用成功的方法
                $scope.member_info = res.member //绑定会员相关数据
                // console.log("会员相关信息："+ $scope.member_info);
                //$scope.top_info = true; //切换已登录的模板
                $scope.no_user_infos = false;
                // $scope.no_user_infos = false;//显示会员信息区域
                Storage.ls_set("user_infos",$scope.member_info);//将会员信息本地存储
                $scope.modal.hide();//将会员信息本地存储
                //$state.go("tab.confirm_order",{id:$scope.coupon_id});//跳转对应的优惠券详情页面//////////////////////////
                //隐藏登录入口
                $scope.no_login = false;
                //清除相关用户信息
                $scope.user_info.user_num = "";
                $scope.user_info.test_code = "";

                //记住密码（防止验证码登录后修改密码报错）
                $scope.id_pwd = {
                  user_num:mobile,
                  user_pwd:''
                };
                Storage.ls_set("user&pwd",$scope.id_pwd);//记住账号及密码

                $cordovaToast.show('登录成功!', 'long', 'center');
                break;
              case 10201:
                // alert("");
                $cordovaToast.show('验证码失效或错误!', 'long', 'center');
                break;
              case 10202:
                // alert("");
                $cordovaToast.show('该手机尚未注册', 'long', 'center');
                break;
              case 10203:
                // alert("");
                $cordovaToast.show('手机号已经被注册', 'long', 'center');
                break;
              case 10204:
                // alert("");
                $cordovaToast.show('手机号或者密码错误', 'long', 'center');
                break;
              default:
                // alert("");
                $cordovaToast.show('出错了，稍后再试', 'long', 'center');
            }
          })
        }else{//手机号错误
          $scope.test_code_tc = "请输入6位正确的验证码"
        }
      }else{//验证码未填或填错；
        $scope.phone_tc = "请输入正确的手机号码"
      }
    }
    //清除验证状态
    $scope.phone_test = function(){//手机号码状态清除
      $scope.phone_tc = " ";
      //账号密码登录状态
      $scope.reg_notice_phone = "";//手机号正则状态清除
      $scope.pwd_login_res = "";//登陆结果状态
    }
    $scope.verification_test = function(){//验证码状态清除
      $scope.test_code_tc = " ";
      //账号密码登录状态
      $scope.reg_notice_pwd = "";//pwd正则状态清除
      $scope.pwd_login_res = "";//登陆结果状态
    }

//账号密码登录
    $scope.n_user_info = {};
    $scope.login_pwd = function(){
      
      var p_user = $scope.n_user_info.user_num;
      var P_pwd = $scope.n_user_info.user_pwd;
      //正则验证；
      // var reg_pwd = /^[a-zA-Z]\w{5,17}$/;
      var reg_mobile = /^\d{5,}$/;

      if(reg_mobile.test(p_user)){//手机号验证通过
        if(P_pwd&&P_pwd.length>7){//密码正则通过
          $ionicLoading.show({
            template: '正在登录中...'
          });
          var md5_pwd = md5.createHash(P_pwd);
          // console.log(md5_pwd);
          //进行登录
          loginModule.n_login(p_user,md5_pwd).then(function(res){
            $ionicLoading.hide();
            // console.log("会员细信息："+JSON.stringify(res));
            switch(res.result){//10200 //请求成功!10201 // 验证码失效10202 // 该手机尚未注册!10203 // 手机号已经被注册10204 //手机号或者密码错误!
              case 10200:
                // alert("请求成功");
                //显示会员相关信息
                $scope.member_info = res.member;
                Storage.ls_set("user_infos",res.member);
                $scope.no_user_infos = false;//显示个人信息这块
                $scope.no_login = false//关闭登录入口
                //隐藏登录
                $scope.modal.hide();
                //$state.go("tab.confirm_order",{id:$scope.coupon_id});//跳转对应的优惠券详情页面//////////////////////////
                // 记住密码；
                if($scope.ischecked){
                  // alert("记住密码")
                  Storage.ls_set("user&pwd", $scope.n_user_info);//记住账号及密码
                }else{
                  Storage.ls_delete("user&pwd");//账号
                  // alert("删除密码")
                  $scope.n_user_info = {};//删除账号及密码
                }
                $cordovaToast.show('登录成功!', 'long', 'center');
                break;
              case 10201:
                // alert("验证码失效");
                $scope.pwd_login_res = "验证码失效或错误"
                break;
              case 10202:
                // alert("该手机尚未注册");
                $scope.pwd_login_res = "该手机尚未注册"
                break;
              case 10203:
                // alert("手机号已经被注册");
                $scope.pwd_login_res = "手机号已经被注册"
                break;
              case 10204:
                // alert("手机号或者密码错误");
                $scope.pwd_login_res = " 手机号或者密码错误"
                break;
              default:
                // alert("出错了，稍后再试");
                $scope.pwd_login_res = "出错了，稍后再试"
            }
           
          })
        }else{//密码正则未通过
           $scope.reg_notice_pwd = "数字和者字母（6到18位）"
        }
      }else{//手机号正则不通过
        $scope.reg_notice_phone = "手机号不正确"
      }

    }
  //获取或设置复选框是否选中
  $scope.ischecked = false;
  //点击切换显密码
  $scope.show_pwd_value = "显示"
  $scope.show_pwd = function(){
    var input = document.getElementById("pwd");
    if(input.type == "text"){
      // console.log("pwd")
      input.type = "password";
      $scope.show_pwd_value = "显示"
    }else{
      // console.log("text")
      input.type = "text";
      $scope.show_pwd_value = "隐藏"
    }

  }

   //注册模块
  $scope.register_info = {};//存放用户注册信息
  $scope.register = function(){
   
    //正则验证
    var r_mobile = $scope.register_info.phone
    var r_pwd = $scope.register_info.pwd;
    var r_code = $scope.register_info.code;
    var _mobile = /^\d{5,}$/.test(r_mobile);
    var _code = /\d{6}/.test(r_code);
    var area = document.getElementById('mcoupon_ZC_area').value;
    // alert(area);
    if(_mobile){
      if(r_pwd && r_pwd.length>7 ){
        if(_code){
          $ionicLoading.show({
            template: '正在注册中...'
          });
          var params = {
            m_phone : r_mobile,
            code : r_code ,
            m_pass : md5.createHash( r_pwd ),
            area:area
          };
          loginModule.register(params).then(function(res){
            // console.log("注册结果"+JSON.stringify(res));
            $ionicLoading.hide();
            switch(res.result){
              case 10200:
                // alert("注册成功,马上登录");
                $scope.change_page(0);//切换至登录模块
                $cordovaToast.show('注册成功,马上登录!', 'long', 'center');
                break;
              case 10201:
                $scope.r_pwd_login_res_code = "验证码失效或错误";
                break;
              case 10202:
                $scope.r_pwd_login_res = "该手机尚未注册";
                break;
              case 10203:
                $scope.r_pwd_login_res = "手机号已经被注册";
                break;
              case 10204:
                $scope.r_pwd_login_res = " 手机号或者密码错误";
                break;
              default:
                $scope.r_pwd_login_res = "出错了，稍后再试";
            }
          })
        }else{
          $ionicPopup.alert({
            title: '提示',
            template: '请输入6位数字验证码！'
          });
        }
      }else{
        // alert("密码为8位以上数字或字母")
        $scope.r_pwd_num = "密码为8位以上数字或字母"
      }
    }else{
      // alert("手机号码不正确")
      $scope.r_phone_num = "手机号码不正确"
    }
   
  }
  //清除注册提示状态
  $scope.hide_notice = function(){
    $scope.r_phone_num = "";
    $scope.r_pwd_num = "";
    $scope.r_pwd_login_res_code = "";
    $scope.r_pwd_login_res = "";
  }
  // 验证码(注册模块)
  $scope.register_code = function(e){
    var phone =  $scope.register_info.phone;
    var area = document.getElementById('mcoupon_ZC_area').value;
    // alert(area);
    // alert(phone);
    if ($scope.captcha.paraevent) {
      if (Common.checkMobile(phone)){
        $ionicLoading.show({
          template: '获取验证码...'
        });
        //调取验证码服务；
        loginModule.reg_captcha(phone,area).then(function(res){
          $ionicLoading.hide();
          // console.log(res);
          if(res.result == "10203"){
            $scope.r_pwd_login_res = "手机号已经注册，请直接登录";
          }else{
            Common.countDown($scope.captcha);
          }
        })
      }else{
        //手机号码不对；
      }
    } else {
        e.preventDefault();
    }
  }
  //重置验证码提示消息
  $scope.set_code_notice = function(){
     $scope.r_pwd_login_res = " "
  }
  //切换密码
  $scope.ischecked = true;//初始化为记住密码状态
  $scope.toggle_pwd = function(){
    if($scope.ischecked){
      $scope.ischecked = false;
    }else{
      $scope.ischecked = true;
    }
  }

})
//确认订单
.controller('confirm_orderCtrl',function($cordovaToast,$stateParams,$scope,$ionicHistory,$cordovaToast,Storage,$ionicLoading,$state,mineModule){
  $scope.goback=function(){
    $ionicHistory.goBack();
  }
   $scope.coupon_id = $stateParams.id;
  //  console.log("优惠券："+ $scope.coupon_id );
  //通过ID获取详情
  $scope.get_order = function(){
     var params = {
      goodsId:$scope.coupon_id
    }
    mineModule.http("getGoodDetail",params).then(function(res){
      // console.log("确认订单："+JSON.stringify(res))
      if( res.code == 10000 ){
        $scope.coupons_details = res.info
        $scope.levelsNo = res.info.levelsNo;//商品的等级
        console.log("商品等级："+$scope.levelsNo);
        //商品数量的加减
			  $scope.max_count = $scope.coupons_details.memberSaleMaxNum;//限购的最大值
			  $scope.good_count = 1;//订单至少购买一件
			  $scope.price = $scope.coupons_details.payMoney//后台获取(单价)
			  $scope.inte = $scope.coupons_details.payPoint//后台获取（单个需要的积分）
			  //初始化显示计算金额（按一份来算）
			  $scope.Total_price = $scope.price;
			  $scope.Total_inte = $scope.inte*$scope.good_count ;
        
      }else{
        $cordovaToast.show('获取数据出错了'+res.code, 'long', 'center'); 
      }
    })
  }
  $scope.info = function(){
  	if(Storage.ls_get("user_infos")){
			var params = {
				memberUUID:JSON.parse(Storage.ls_get("user_infos")).memberuuid
	    }
	    mineModule.http("getMember",params).then(function(res){
	    	if(res.code = 10000){
          $scope.info = res.info
          $scope.card_name = res.info.levelNo;//获取会员当前的会员等级
          console.log("当前的会员等级："+$scope.card_name);
	    		// console.log("会员的积分信息："+JSON.stringify(res));
	    		$scope.all_inte =  res.info.usableBonus //后台获取（会员当前的总积分 ，购买商品的积分不能大于总积分）
	    	}else{
          $cordovaToast.show('获取数据出错了 '+res.code, 'long', 'center'); 
	    	}
	    
	    })
		}else{
      $cordovaToast.show('暂时未获取到会员信息，请重新登录再试', 'long', 'center');
		}
  }
  //获取订单详情；
  $scope.get_order() 
  //获取会员积分
	$scope.info();
	
  

  $scope.add = function(){
    if($scope.max_count > $scope.good_count){
    	$scope.good_count++;
	  	$scope.Total_price = ($scope.price*$scope.good_count).toFixed(2);
	    $scope.Total_inte = $scope.inte*$scope.good_count;
    }else{
			$cordovaToast.show('不能超过最大限购数!', 'long', 'center');
    }
  }
  $scope.reduce = function(){
    if( $scope.good_count > 1 ){
      $scope.good_count--;
    	$scope.Total_price = ($scope.price*$scope.good_count).toFixed(2);
      $scope.Total_inte = $scope.inte*$scope.good_count ;
    }else{
			$cordovaToast.show('至少兑换一件该商品!', 'long', 'center');
    }
  }

    //提交订单去支付
  $scope.go_pay = function(){
    //遮罩层；
    $ionicLoading.show({
      template: '努力获取订单中'
    });
    var h_AppTimer = setTimeout(function(){//超时30秒自动关闭遮罩层；
      $ionicLoading.hide();
      clearTimeout(h_AppTimer);
    },30000);
    //先判断等级是否匹配
    if( $scope.levelsNo.indexOf($scope.card_name) != -1 ){
      //再判断会员积分是否够用
      if( $scope.all_inte >= $scope.Total_inte ){//积分够用
        var obj = document.getElementsByName("pay")
        for(var i=0; i<obj.length; i ++){
          if(obj[i].checked){
            $scope.pay_value = obj[i].value;
          }
        }
        var order_params={
          "trade_name":$scope.coupons_details.couponInfo.couponName,//订单名字
          "trade_num":$scope.good_count,//订单数量
          "memberUUID":JSON.parse(Storage.ls_get("user_infos")).memberuuid,
          "member_id":JSON.parse(Storage.ls_get("user_infos")).m_id,
          "member_card":$scope.info.cardNo,
          "member_phone": $scope.info.mobile,
          "total_amount":parseFloat($scope.Total_price) ,   /////////////////////   记得后面的重新支付也要改（控制器：pay_resCtrl）；
          "total_point": $scope.Total_inte,
          "total_fee":parseFloat($scope.Total_price)*100,   ////////////////////////////  记得后面的重新支付也要改（控制器：pay_resCtrl）；
          "tradeDetails": [{
            "goodsid": $scope.coupon_id,
            "goodsnum": $scope.good_count,
            "goodsprice": $scope.price,
            "goodspoint": $scope.Total_inte
          }],
          "goodsList":[{
            "goodsId": $scope.coupon_id,
            "goodsName":$scope.coupons_details.couponInfo.couponName ,
            "price": $scope.price,
            "point": $scope.Total_inte,
            "goodsCount":$scope.good_count,
          }]
        }
        if( $scope.pay_value == "1"){//支付宝
  //			alert(JSON.stringify(order_params));
          mineModule.pay("aliPay",order_params).then(function(res){
            $ionicLoading.hide();//关闭遮罩层
            console.log("返回的订单信息："+JSON.stringify(res));
            if(res.code == 10200){//创建订单成功
              //区分0元支付   实际金额支付；
              var cc = res.out_trade_no;
              if(res.order){
                var html = res.order;
                cordova.plugins.alipay.payment(html,function(success){
                  $state.go("tab.pay_res",{id:"succ"+'.'+cc})
                }, function(error){
                  $cordovaToast.show(JSON.stringify(error), 'long', 'center');
                  // $state.go("tab.h_pay_res",{id:"erre"+'.'+html});//err
                  // Storage.ls_set("HTML",html);
                });
              }else{
                $ionicLoading.hide();
                $cordovaToast.show('购买成功~', 'long', 'center').then(function(succ){
                  $state.go("tab.pay_res",{id:"succ"+'.'+cc});
                });
              }
            }else if(res.code == 10403){// 超出最大限购
              $ionicLoading.hide();
              $cordovaToast.show('创建订单失败,您已经累计超过最大限购~', 'long', 'center');
            }else{//创建订单失败
              $ionicLoading.hide();
              $cordovaToast.show('创建订单失败!('+res.code+')', 'long', 'center')
            }
          
          })
        }else if( $scope.pay_value == "2" ){//微信
          // alert(2)
          mineModule.pay("wxPayAPP",order_params).then(function(res){
            $ionicLoading.hide();
            console.log("微信支付相关参数：" + JSON.stringify( res ) )
            if(res.code == 10200){//创建订单成功
              //区分0元支付   实际金额支付；
              var cc = res.out_trade_no;
              if(res.app_params){//唤起微信支付；
                var params ={
                  appid:res.app_params.appid, //appid
                  package :res.app_params.package,//Sign=WXPay
                  partnerid:res.app_params.partnerid, // merchant id
                  prepayid:res.app_params.prepayid, // prepay id
                  noncestr:res.app_params.noncestr, // nonce
                  timestamp:res.app_params.timestamp, // timestamp
                  sign:res.app_params.sign // signed string
                };
                  
                Wechat.sendPaymentRequest(params, function () {
                  $state.go("tab.pay_res",{id:"succ"+'.'+cc});
                }, function (reason) {
                  // $state.go("tab.h_pay_res",{id:"erre"+'.'+params});//err
                  // Storage.ls_set("WX_params",params);
                  $cordovaToast.show(reason, 'long', 'center')
                });
                
              }else{//0 元支付；
                $ionicLoading.hide();
                $cordovaToast.show('购买成功~', 'long', 'center').then(function(succ){
                  $state.go("tab.pay_res",{id:"succ"+'.'+cc});
                });
              }
            }else if(res.code == 10403){// 超出最大限购
              $ionicLoading.hide();
              $cordovaToast.show('创建订单失败,您已经累计超过最大限购~', 'long', 'center');
            }else{//创建订单失败
              $ionicLoading.hide();
              $cordovaToast.show('创建订单失败!('+res.code+')', 'long', 'center')
            }
          
          })

        }else{//既不是支付宝也不是微信
          $ionicLoading.hide();
          return;
        }
        
      }else{//积分不够用
        $ionicLoading.hide();
        $cordovaToast.show('您的积分不够!', 'long', 'center')
      }

    }else{
      $ionicLoading.hide(); 
      $cordovaToast.show('您的会员等级暂时不能兑换该商品~', 'long', 'center')
    }
  	
  }

})
//支付状态
.controller('pay_resCtrl',function(Storage,$scope,$ionicTabsDelegate,$ionicHistory,$location,$state,$stateParams){
  $scope.goback=function(){
    $ionicHistory.goBack();
  }
 	if($stateParams.id){//成功
// 	alert($stateParams.id.split(" ")[0]);
   	if($stateParams.id.split(".")[0] == "succ"){
	 		$scope.succ = true;
	 		$scope.err = false;
	 		$scope.id = $stateParams.id.split(".")[1];
//	 		alert("查看详情："+	$scope.id)
   	}
 		if($stateParams.id.split(".")[0] == "erre"){//支付失败
	 		$scope.succ = false;
	 		$scope.err = true;
//	 		$scope.re_pay = $stateParams.id.split(".")[1];
//	 		alert("重新支付："+$scope.re_pay)
	 		
	 	}
 	}
 	
 	
 	$scope.re_pay = function(){
 		var HTML = Storage.ls_get("HTML");
// 		alert(HTML);
		cordova.plugins.alipay.payment(HTML,function(success){
			var aa = JSON.stringify(success).replace(/\\/g,"")
			var num = aa.indexOf("out_trade_no");
			var cc = aa.substring(num+15,num+51);
			$state.go("tab.pay_res",{id:"succ"+'.'+cc})
			Storage.ls_delete("HTML");//支付成功后删除之前的缓存
		}, function(error){
			$state.go("tab.pay_res",{id:"erre"+'.'+$scope.re_pay});//err
		});
  } 
  
  //查看订单详情
  
})

.filter('shijian', function() { //可以注入依赖
    return function(text) {
        // return text.substr(0, 10);
        return text.split(" ")[0];
    }
})
.filter('sxsj', function() { //可以注入依赖
    return function(num) {
      if( num == 1){
        return "立即生效"
      }else{
        return "次日生效"
      }
    }
})
.filter('rule', function() { //可以注入依赖
    return function(te) {
      return "满"+te+"元可用"
    }
})
.filter('card', function() { 
    return function(t) {
      return t.join(" 、")
    }
})
